<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        overflow: hidden;
        margin: 0 100px;
      }
      .box1,
      .box2 {
        width: 147px;
        height: 220px;
        border: 1px solid #999;
        padding: 10px;
        margin-right: 100px;
        float: left;
      }
      img {
        width: 100%;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <!-- 必须在被拖拽的元素上添加draggable="true" -->
      <div class="box1">
        <img
          draggable="true"
          id="img"
          src="./images/test.jpg"
          alt="picture-drag"
        />
      </div>
      <div class="box2"></div>
    </div>
  </body>
  <script>
    var box1 = document.querySelector(".box1");
    var box2 = document.querySelector(".box2");
    var img = document.querySelector("#img");

    // 阻止默认行为
    box1.ondragover = function (e) {
      e.preventDefault();
    };
    box2.ondragover = function (e) {
      e.preventDefault();
    };
    
    img.ondragstart = function (e) {
      //   console.log(e.target.id);
      //   console.log(e);

      // 将拖拽的目标对象存入dataTransfer中（一定要先给目标对象id值）
      e.dataTransfer.setData("imgTarget", e.target.id);
      // 获取存入在dataTransfer中的数据
      //   console.log(e.dataTransfer.getData("imgTarget"));
    };


    // 将目标对象存入box2中
    // （要想让ondrop发挥作用，必须在ondragover事件中进行默认行为的阻止）
    box2.ondrop = function (e) {
      this.appendChild(
        document.getElementById(e.dataTransfer.getData("imgTarget"))
      );
    };

    // 将目标对象存入box1中（先从box1拖拽到box2再从box2拖拽到box1）
    box1.ondrop = function (e) {
      this.appendChild(
        document.getElementById(e.dataTransfer.getData("imgTarget"))
      );
    };
  </script>
</html>
